package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.exceptions.LyException;
import com.leyou.common.utils.JsonUtils;
import com.leyou.item.dto.SpecParamDTO;
import com.leyou.item.dto.SpuDetailDTO;
import com.leyou.item.entity.Spu;
import com.leyou.item.entity.SpuDetail;
import com.leyou.item.mapper.SpuDetailMapper;
import com.leyou.item.mapper.SpuMapper;
import com.leyou.item.service.SpecParamService;
import com.leyou.item.service.SpuDetailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class SpuDetailServiceImpl extends ServiceImpl<SpuDetailMapper, SpuDetail> implements SpuDetailService {
    @Autowired
    private SpecParamService specParamService;
    @Autowired
    private SpuMapper spuMapper;

    //根据id查询spuDetail value
    @Override
    public List<SpecParamDTO> querySpecValues(Long id, Boolean searching) {
        //根据id查询spuDetail
        SpuDetail byId = getById(id);
        //获取键值对
        Map<Long, Object> specvalues = JsonUtils.toMap(byId.getSpecification(), Long.class, Object.class);
            //根据id信息查询spu
        Spu spu = spuMapper.selectById(id);
        List<SpecParamDTO> params = specParamService.SpecParamByIds(spu.getCid3(), null, searching);
        for (SpecParamDTO param : params) {
            param.setValue(specvalues.get(param.getId()));
        }
        return params;
    }

    @Override
    public SpuDetailDTO queryById(Long id) {
        SpuDetail detail = getById(id);
        if (detail == null) {
            throw new LyException(400, "商品id不存在！");
        }
        return new SpuDetailDTO(detail);
    }
}